package cn.com.woxitech.dev.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.UUID;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.JsonNode;

import cn.com.woxitech.dev.common.Const;
import cn.com.woxitech.dev.common.EncryptionUtils;
import cn.com.woxitech.dev.common.HttpClientUtils;
import cn.com.woxitech.dev.common.JSONUtils;
import cn.com.woxitech.dev.common.weixin.PayCommonUtil;
import cn.com.woxitech.dev.dao.gen.WeixinApiAccessTokenMapper;
import cn.com.woxitech.dev.dao.gen.WeixinJsapiTicketMapper;
import cn.com.woxitech.dev.dao.gen.WmUserMapper;
import cn.com.woxitech.dev.model.WXSDKConfig;
import cn.com.woxitech.dev.model.WeixinWebAccessToken;
import cn.com.woxitech.dev.model.gen.WeixinApiAccessToken;
import cn.com.woxitech.dev.model.gen.WeixinApiAccessTokenExample;
import cn.com.woxitech.dev.model.gen.WeixinJsapiTicket;
import cn.com.woxitech.dev.model.gen.WeixinJsapiTicketExample;
import cn.com.woxitech.dev.model.gen.WmUser;
import cn.com.woxitech.dev.model.gen.WmUserExample;

@Service
public class WeixinService {
	
	@Autowired
	private UserService userService;
	
	@Autowired
	SettingService settingService;
	
	@Autowired
	private WeixinApiAccessTokenMapper weixinApiAccessTokenMapper;
	
	@Autowired
	private WmUserMapper wmUserMapper;
	
	@Autowired
	private WeixinJsapiTicketMapper ticketMapper;
	
	public WeixinApiAccessToken getWeixinApiAccessTokenByName(String name) {
		// TODO Auto-generated method stub
		WeixinApiAccessTokenExample e = new WeixinApiAccessTokenExample();
		e.createCriteria().andNameEqualTo(name);
		List<WeixinApiAccessToken> list = this.weixinApiAccessTokenMapper.selectByExample(e);
		if(list == null || list.isEmpty()){
			return null;
		}else{
			return list.get(0);
		}
	}

	
	private String getAccessTokenByAppid(String appid) throws Exception {
		// TODO Auto-generated method stub
		
		String accesstoken = null;
		WeixinApiAccessToken wxaat = new WeixinApiAccessToken();
		
		WeixinApiAccessTokenExample e = new WeixinApiAccessTokenExample();
		e.createCriteria().andAppidEqualTo(appid);
		List<WeixinApiAccessToken> list_WeixinApiAccessToken = weixinApiAccessTokenMapper.selectByExample(e);
		if(list_WeixinApiAccessToken == null || list_WeixinApiAccessToken.isEmpty()){
			throw new Exception("wxaat is null");
		}else{
			wxaat = list_WeixinApiAccessToken.get(0);
		}
				
		//wxaat 必须不为空

		//判断是否存在accessToken
		if(wxaat.getAccessToken() != null && !wxaat.getAccessToken().equals("")){
			if((System.currentTimeMillis() - wxaat.getCreatetime().getTime())/1000 < wxaat.getExpiresIn()){
				//未过期
				accesstoken = wxaat.getAccessToken();
			}
		}
		
		if(accesstoken == null){
			String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+
					wxaat.getAppid()+
					"&secret=" + 
					wxaat.getSecretid();
			String resp = HttpClientUtils.sendGETSSL(url);
			//{"access_token":"ACCESS_TOKEN","expires_in":7200}
			//{"errcode":40013,"errmsg":"invalid appid"}
		    JsonNode _resp = JSONUtils.toJson(resp);
		    accesstoken = _resp.get("access_token").textValue();
		    
		    //将accesstoken存入数据库
		    WeixinApiAccessToken record = new WeixinApiAccessToken();
		    record.setAppid(appid);
		    record.setCreatetime(new Date(System.currentTimeMillis()));
		    record.setAccessToken(accesstoken);
		    weixinApiAccessTokenMapper.updateByPrimaryKeySelective(record);
		}

		return accesstoken;
	}

	public WmUser getWmUserByUnionId(String unionid) {
		// TODO Auto-generated method stub
		WmUserExample e = new WmUserExample();
		e.createCriteria().andWxUnionidEqualTo(unionid);
		List<WmUser> list = this.wmUserMapper.selectByExample(e);
		if(list == null || list.size() ==0){
			return null;
		}else{
			return list.get(0);	
		}
		
	}

	
	public boolean checkWeixinWebAccessToken(String accesstoken, String openid) throws Exception{
		//{"errcode":40001,"errmsg":"invalid credential, access_token is invalid or not latest, hints: [ req_id: D9SYja0774ns80 ]"}
		//{ "errcode":0,"errmsg":"ok"}		
		
		String url = "https://api.weixin.qq.com/sns/auth?access_token="+accesstoken+"&openid=" + openid;
		
		String resp = HttpClientUtils.sendGETSSL(url);
		
		JsonNode _resp = JSONUtils.toJson(resp);
		
		if(_resp.has("errmsg")){
			if(_resp.get("errmsg").asText().equals("ok")){
				return true;
			}
		}
		
		return false;
	}
	
	public WeixinWebAccessToken getWeixinWebAccessToken(String code) throws Exception {
		// TODO Auto-generated method stub
		
		WeixinWebAccessToken at = new WeixinWebAccessToken();
		
		WeixinApiAccessToken waat = new WeixinApiAccessToken();
		WeixinApiAccessTokenExample e = new WeixinApiAccessTokenExample();
		e.createCriteria().andAppidEqualTo(Const.APPID);
		List<WeixinApiAccessToken> list_WeixinApiAccessToken = weixinApiAccessTokenMapper.selectByExample(e);
		if(list_WeixinApiAccessToken == null || list_WeixinApiAccessToken.isEmpty()){
			throw new Exception("wxaat is null");
		}else{
			waat = list_WeixinApiAccessToken.get(0);
		}

		
		
		
		
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
				+ Const.APPID
				+ "&secret="
				+ waat.getSecretid()
				+ "&code="
				+ code
				+ "&grant_type=authorization_code";
		
		//获取
		String resp = HttpClientUtils.sendGETSSL(url);
		
		JsonNode _resp = JSONUtils.toJson(resp);
	    
		if(_resp.has("errcode")){
		//{"errcode":40029,"errmsg":"invalid code, hints: [ req_id: SGOnKA0586ns57 ]"}
		//TODO: invalid code，参数错误，
			throw new Exception("invalid_code");
			
		}else{
			at.setAccess_token(_resp.get("access_token").textValue());
			at.setExpires_in(_resp.get("expires_in").intValue());
			at.setRefresh_token(_resp.get("refresh_token").textValue());
			at.setOpenid(_resp.get("openid").textValue());
			at.setScope(_resp.get("scope").textValue());
			if(_resp.has("unionid")){
				at.setUnionid(_resp.get("unionid").textValue());
			}
		}
		
		return at;
	}

	public WXSDKConfig getWeiXinSDKConfig(String calledUrl) {
		// TODO Auto-generated method stub
		
		
		String timestamp = "" + System.currentTimeMillis()/1000;
		String signature="";
		String noncestr = PayCommonUtil.CreateNoncestr();
		
		String jsapi_ticket = this.getJsApiTicket();
		
//				jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg
//				&noncestr=Wm3WZYTPz0wzccnW
//				&timestamp=1414587457
//				&url=http://mp.weixin.qq.com?params=value
//		
		String s1 = "jsapi_ticket="+jsapi_ticket
					+ "&noncestr=" + noncestr
					+ "&timestamp=" + timestamp
					+ "&url=" + calledUrl;

		signature = EncryptionUtils.SHA1(s1);
		
		WXSDKConfig config = new WXSDKConfig();
		
		config.setAppId(Const.APPID);
		config.setDebug("false");
		config.setTimestamp(timestamp);
		config.setSignature(signature);
		config.setNonceStr(noncestr);
		config.setJsApiList(new ArrayList<String>());
		
		return config;
	}
	public String getJsApiTicket() {
		// TODO Auto-generated method stub
		String jsApiTicket ="";
		WeixinJsapiTicketExample e = new WeixinJsapiTicketExample();
		e.setOrderByClause("id desc limit 0,1");
		List<WeixinJsapiTicket> list = ticketMapper.selectByExample(e);
		if(list == null || list.isEmpty()){
			//从微信服务器取accessToken
			jsApiTicket = fetchJSApiTicketFromWeiXin(null);
				
		}else{
			//判断是否过期
			if((System.currentTimeMillis() -list.get(0).getTime())/1000 > list.get(0).getExpiresIn()){
				//从微信服务器取accessToken
				jsApiTicket = fetchJSApiTicketFromWeiXin(list.get(0));
			}else{
				jsApiTicket = list.get(0).getTicket();
			}
			
		}
		return jsApiTicket;
		
	}
	

	private String fetchJSApiTicketFromWeiXin(WeixinJsapiTicket jsApiTicket) {
		// TODO Auto-generated method stub
		String ticket = "";
		WeixinJsapiTicket temp = null;
		if(jsApiTicket == null){
			temp = new WeixinJsapiTicket();	
		}else{
			temp = jsApiTicket;
		}
		
		String access = this.getAccessToken();
		
//		https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi
		String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="
				+ access
				+ "&type=jsapi";
//		{
//			"errcode":0,
//			"errmsg":"ok",
//			"ticket":"bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA",
//			"expires_in":7200
//			}
		
		try {
			//{"access_token":"ACCESS_TOKEN","expires_in":7200}
			String resp = HttpClientUtils.sendGETSSL(url);
			
			JsonNode resp_json = JSONUtils.toJson(resp);
			temp.setErrcode(resp_json.get("errcode").intValue());
			temp.setErrmsg(resp_json.get("errmsg").textValue());
			temp.setTime(System.currentTimeMillis());
			temp.setExpiresIn(resp_json.get("expires_in").intValue());
			temp.setTicket(resp_json.get("ticket").textValue());
			ticket = temp.getTicket();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		
		
		if(jsApiTicket != null){
			//更新数据库表
			this.ticketMapper.updateByPrimaryKeySelective(temp);
		}else{
			//添加新记录
			this.ticketMapper.insertSelective(temp);
		}
		
		return ticket;
	}
	public String getAccessToken() {
		// TODO Auto-generated method stub
		String accessToken ="";
		WeixinApiAccessTokenExample e = new WeixinApiAccessTokenExample();
		
		e.createCriteria().andAppidEqualTo(Const.APPID);
		List<WeixinApiAccessToken> list = weixinApiAccessTokenMapper.selectByExample(e);
		if(list == null || list.isEmpty()){
			//从微信服务器取accessToken
			accessToken = fetchAccessTokenFromWeiXin(null);
				
		}else{
			//判断是否过期
			if((System.currentTimeMillis() -list.get(0).getCreatetime().getTime())/1000 > list.get(0).getExpiresIn()){
				//从微信服务器取accessToken
				accessToken = fetchAccessTokenFromWeiXin(list.get(0));
			}else{
				accessToken = list.get(0).getAccessToken();
			}
			
		}
		return accessToken;
		
	}
	
	
	public WeixinApiAccessToken getApiAccessTokenByAppId(String appid){

		WeixinApiAccessToken wxaat = new WeixinApiAccessToken();
		
		new WeixinApiAccessToken();
		
		WeixinApiAccessTokenExample e = new WeixinApiAccessTokenExample();
		e.createCriteria().andAppidEqualTo(appid);
		List<WeixinApiAccessToken> list_wxaat = weixinApiAccessTokenMapper.selectByExample(e);
		
		if(list_wxaat == null || list_wxaat.isEmpty()){
			return null;
		}else{
			return list_wxaat.get(0);	
		}
	}
	
	private String fetchAccessTokenFromWeiXin(WeixinApiAccessToken weixinAccessToken) {
		// TODO Auto-generated method stub
		String accessToken = "";
		WeixinApiAccessToken temp = null;
		if(weixinAccessToken == null){
			temp = new WeixinApiAccessToken();	
		}else{
			temp = weixinAccessToken;
		}
		
		
		WeixinApiAccessToken wxaat = getApiAccessTokenByAppId(Const.APPID);
		
		
		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
				+ wxaat.getAppid()
				+ "&secret="
				+ wxaat.getSecretid();
		
		try {
			//{"access_token":"ACCESS_TOKEN","expires_in":7200}
			String resp = HttpClientUtils.sendGETSSL(url);
			

			JsonNode resp_json = JSONUtils.toJson(resp);
			
			temp.setAccessToken(resp_json.get("access_token").textValue());
			temp.setCreatetime(new Date(System.currentTimeMillis()));
			temp.setExpiresIn(resp_json.get("expires_in").intValue());
			accessToken = temp.getAccessToken();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		
		
		if(weixinAccessToken != null){
			//更新数据库表
			this.weixinApiAccessTokenMapper.updateByPrimaryKeySelective(temp);
		}else{
			//添加新记录
			this.weixinApiAccessTokenMapper.insertSelective(temp);
		}
		
		return accessToken;
	}
	public WmUser getUserInfoFromWeiXin(WmUser wu) {
		// TODO Auto-generated method stub
		
		//https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
		
		String url = "https://api.weixin.qq.com/sns/userinfo?access_token="
				+ wu.getuAccessToken()
				+ "&openid="
				+ wu.getWxOpenid()
				+ "&lang=zh_CN";
		
		String resp = "";
		
		try{
			
			resp = HttpClientUtils.sendGETSSL(url);
			resp = new String(resp.getBytes("ISO-8859-1"), "UTF-8");

			JsonNode resp_json = JSONUtils.toJson(resp);
			
//			{
//				   "openid":" OPENID",
//				   " nickname": NICKNAME,
//				   "sex":"1",
//				   "province":"PROVINCE"
//				   "city":"CITY",
//				   "country":"COUNTRY",
//				    "headimgurl":    "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46", 
//					"privilege":[
//					"PRIVILEGE1"
//					"PRIVILEGE2"
//				    ],
//				    "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
//				}
			
//			{"errcode":42001,"errmsg":"access_token expired, hints: [ req_id: GVk3IA0853ns86 ]"}
			
			if(resp_json.has("errcode")){
				//access_token expired
				String refeshToken = wu.getuRefreshToken();

				String access_token = this.refreshWebXinWebAccessToken(refeshToken);
				wu.setuAccessToken(access_token);
				url = "https://api.weixin.qq.com/sns/userinfo?access_token="
						+ wu.getuAccessToken()
						+ "&openid="
						+ wu.getWxOpenid()
						+ "&lang=zh_CN";
				
				resp = HttpClientUtils.sendGETSSL(url);
				resp = new String(resp.getBytes("ISO-8859-1"), "UTF-8");
				resp_json = JSONUtils.toJson(resp);
			}
			
			wu.setLastlogin(new Date(System.currentTimeMillis()));
			wu.setName(resp_json.get("nickname").textValue());
			wu.setWxCity(resp_json.get("city").textValue());
			wu.setWxProvince(resp_json.get("province").textValue());
			wu.setWxCountry(resp_json.get("country").textValue());
			wu.setWxHeadimgurl(resp_json.get("headimgurl").textValue());
			wu.setWxNickname(resp_json.get("nickname").textValue());
			wu.setWxOpenid(resp_json.get("openid").textValue());
//			wu.setWxPrivilege(wxPrivilege);
			wu.setWxSex(resp_json.get("sex").textValue());

			if(resp_json.has("unionid")){
				wu.setWxUnionid(resp_json.get("unionid").textValue());	
			}else{
				System.out.println("not exist unionid");
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
		
		return wu;
		

	}

	public String refreshWebXinWebAccessToken(String refresh_token) {
		// TODO Auto-generated method stub
		
		try {
			WeixinWebAccessToken at = new WeixinWebAccessToken();
			
			WeixinApiAccessToken waat = getApiAccessTokenByAppId(Const.APPID);
			
			String url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid="+Const.APPID+"&grant_type=refresh_token&refresh_token="+refresh_token;
			
			//获取
			String resp;

			resp = HttpClientUtils.sendGETSSL(url);
		
			JsonNode _resp = JSONUtils.toJson(resp);
		    
			if(_resp.has("access_token")){
				
				WmUser user = new WmUser();
				user.setuAccessToken(_resp.get("access_token").textValue());
				String openid = _resp.get("openid").textValue();
				
				this.userService.updateUserByOpenid(user, openid);
				return _resp.get("access_token").textValue();
				
			}
			
//			{
//				   "access_token":"ACCESS_TOKEN",
//				   "expires_in":7200,
//				   "refresh_token":"REFRESH_TOKEN",
//				   "openid":"OPENID",
//				   "scope":"SCOPE"
//				}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public WmUser getUserInfoFromWeiXin(String access_token, String refresh_token, String openid) {
		// TODO Auto-generated method stub
		WmUser u = new WmUser();
		u.setWxOpenid(openid);
		u.setuAccessToken(access_token);
		u.setuRefreshToken(refresh_token);
		return getUserInfoFromWeiXin(u);
	}

	public WeixinWebAccessToken getWeiXinUserByOpenAPICode(String code) {
		// TODO Auto-generated method stub
		WeixinWebAccessToken wwat = new WeixinWebAccessToken();
		
		WmUser wmUser = null;
		WeixinApiAccessToken waat = getApiAccessTokenByAppId(Const.HJSZX_OPENAPI_APPID);
		
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
		+ Const.HJSZX_OPENAPI_APPID
		+"&secret="
		+ waat.getSecretid()
		+ "&code="
		+ code
		+ "&grant_type=authorization_code";
		
		String resp = "";
		try{
			
			resp = HttpClientUtils.sendGETSSL(url);
			resp = new String(resp.getBytes("ISO-8859-1"), "UTF-8");
			
			JsonNode _resp = JSONUtils.toJson(resp);
			
			
			
			wwat.setAccess_token(_resp.get("access_token").textValue());
			wwat.setExpires_in(_resp.get("expires_in").intValue());
			wwat.setRefresh_token(_resp.get("refresh_token").textValue());
			wwat.setOpenid(_resp.get("openid").textValue());
			wwat.setScope(_resp.get("scope").textValue());
			wwat.setUnionid(_resp.get("unionid").textValue());
			
			
			
			return wwat;

			
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return null;
	}

	public String getDashangOrderSignInfo(String roomuuid, String unionid, double fee, String appid) {
		// TODO Auto-generated method stub
		
		String SERVER_NOTIFY = "113.224.147.153:9999";
		String out_trade_no = roomuuid+"_"+ unionid + "_"+System.currentTimeMillis();
		String totalFee = ""+fee; 
		String notify_url = "http://"+SERVER_NOTIFY+"/mvc/weixinpay/zbskd/notify";
		String productid = "dashang001";
		SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
		parameters.put("appid", Const.ZBSKD_OPENAPI_APPID);// 公众账号id
		parameters.put("mch_id",  Const.ZBSKD_MCH_ID);// 商户号
		parameters.put("nonce_str", PayCommonUtil.CreateNoncestr());// 随机字符串
		parameters.put("body", "打赏给直播上科大APP");// 商品描述
		parameters.put("out_trade_no", out_trade_no);// 商户订单号
		parameters.put("total_fee", totalFee);// 总金额
		parameters.put("notify_url", notify_url);// 支付成功后回调的action，与JSAPI相同
		parameters.put("trade_type", "NATIVE");// 交易类型
		parameters.put("product_id", productid);// 商品ID。商品号要唯一,trade_type=NATIVE，此参数必传。此id为二维码中包含的商品ID，商户自行定义
		String sign = PayCommonUtil.createSign2("UTF-8", parameters,Const.ZBSKD_MCH_SECRETKEY);
		parameters.put("sign", sign);// 签名
		
		return sign;
	}

	public void saveWeixinAppIdAndSecret(String id, String secret, String name) {
		// TODO Auto-generated method stub
		
		WeixinApiAccessTokenExample e = new WeixinApiAccessTokenExample();
		e.createCriteria().andNameEqualTo(name);
		List<WeixinApiAccessToken> list = this.weixinApiAccessTokenMapper.selectByExample(e);
		if(list == null || list.isEmpty()){
			WeixinApiAccessToken a1 = new WeixinApiAccessToken();
			a1.setAppid(id);
			a1.setSecretid(secret);
			a1.setName(name);
			a1.setCreatetime(new Date(System.currentTimeMillis()));
			
			this.weixinApiAccessTokenMapper.insertSelective(a1);
		}else{
			WeixinApiAccessToken a1 = list.get(0);
			a1.setAppid(id);
			a1.setSecretid(secret);
			a1.setName(name);
			
			this.weixinApiAccessTokenMapper.updateByExampleSelective(a1, e);
		}
	}

	public List<WeixinApiAccessToken> getWeixinApiAccessTokenList() {
		// TODO Auto-generated method stub
		WeixinApiAccessTokenExample e = new WeixinApiAccessTokenExample();
		
		return this.weixinApiAccessTokenMapper.selectByExample(e);
	}

	public WmUser getWeiXinUserAccessToken(String code, WeixinApiAccessToken waat) throws Exception {
		// TODO Auto-generated method stub

		WmUser wu = new WmUser();
		String appid = waat.getAppid();
		String appsecret = waat.getSecretid();
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
				+ appid
				+ "&secret="
				+ appsecret
				+ "&code="
				+ code
				+ "&grant_type=authorization_code&r="+System.currentTimeMillis();
		
		//获取
		String resp ="";
		resp = HttpClientUtils.sendGETSSL(url);
//			{
//			   "access_token":"ACCESS_TOKEN",
//			   "expires_in":7200,
//			   "refresh_token":"REFRESH_TOKEN",
//			   "openid":"OPENID",
//			   "scope":"SCOPE",
//				"unionid": "xzcvzxv"
//			}
		
//			{"errcode":40029,"errmsg":"invalid code, hints: [ req_id: SGOnKA0586ns57 ]"}
		
		
		JSONObject _resp = new JSONObject(resp);
		try{
			wu.setuAccessToken(_resp.getString("access_token"));
			wu.setuExpiresIn(_resp.getInt("expires_in"));
			wu.setuRefreshToken(_resp.getString("refresh_token"));
			wu.setWxOpenid(_resp.getString("openid"));
			wu.setuScope(_resp.getString("scope"));
			if(_resp.has("unionid")){
				wu.setWxUnionid(_resp.getString("unionid"));
			}
			
		}catch(Exception e){
			System.out.println(_resp.toString());
			return null;
		}
		return wu;
		
	}

	public void saveWeiXinUserInfo(WmUser wu) {
		// TODO Auto-generated method stub
//		String n = EmojiFilter.filterEmoji(wu.getName());
		String n = wu.getWxNickname();
		if(n == null || n.length() == 0){
			n = "用户" + System.currentTimeMillis()/1000;
		}
		wu.setName(n);
		wu.setWxNickname(n);
		wu.setCreatetime(new Date(System.currentTimeMillis()));
		wu.setLastlogin(new Date(System.currentTimeMillis()));
		this.wmUserMapper.insertSelective(wu);
	}

	public void updateWmUser(WmUser wmUser) {
		// TODO Auto-generated method stub
		this.wmUserMapper.updateByPrimaryKeySelective(wmUser);
	}


	public WmUser getWeiXinUser(String code, WeixinApiAccessToken app) throws Exception {
		// TODO Auto-generated method stub

		WmUser wu = new WmUser();
		wu = this.getWeiXinUserAccessToken(code,app);
		if(wu == null){//weixin获取用户accesstoken失败，需要重新获取
			throw new Exception("wxnotfound");
		}
		WmUserExample e = new WmUserExample();
		
		if(wu.getWxUnionid() == null){//未绑定开放平台
			e.createCriteria().andWxOpenidEqualTo(wu.getWxOpenid());
			
		}else{//已绑定开放平台
			e.createCriteria().andWxUnionidEqualTo(wu.getWxUnionid());
			
		}
		
		String name = "";
		String headimgurl = "";
		String uuid = "";
		
		
		List<WmUser> users = wmUserMapper.selectByExample(e);
		if(users == null || users.isEmpty()){ //数据库中未找到该用户，跳转不全信息的页面,不全邮箱、或者手机
			WmUser newuser = getUserInfoFromWeiXin(wu);
			newuser.setWxOpenid(wu.getWxOpenid());
			newuser.setuAccessToken(wu.getuAccessToken());
			newuser.setuExpiresIn(wu.getuExpiresIn());
			newuser.setuRefreshToken(wu.getuRefreshToken());
			newuser.setuScope(wu.getuScope());
			newuser.setUuid(UUID.randomUUID().toString());
			this.saveWeiXinUserInfo(newuser);
			name = newuser.getName();
			headimgurl = newuser.getWxHeadimgurl();
			uuid = newuser.getUuid();
		}else{
			WmUser newuserFromWx = getUserInfoFromWeiXin(wu);
			WmUser newuser = users.get(0);
			newuser.setName(newuserFromWx.getWxNickname());
			newuser.setWxNickname(newuserFromWx.getWxNickname());
			newuser.setLastlogin(new Date(System.currentTimeMillis()));
			newuser.setWxHeadimgurl(newuserFromWx.getWxHeadimgurl());
			this.userService.updateUser(newuser);
			name = newuser.getName();
			headimgurl = newuser.getWxHeadimgurl();
			uuid = newuser.getUuid();
		}
		
		wu.setUuid(uuid);
		wu.setName(name);
		wu.setWxHeadimgurl(headimgurl);
		
		return wu;
	}
}
